'use strict';

const Service = require('egg').Service;

class row extends Service {
  // 新增行
  async add(table_id, row, rows) {
    const { app, service } = this;
    const fieldList = await service.field.query(table_id);
    if (!fieldList.length) {
      return;
    }
    const now = Date.now();
    let result = {};
    let rowList = rows;
    if (Array.isArray(row) && row.length) {
      rowList = [ row ];
    }
    if (Array.isArray(rowList) && rowList.length && rowList.every(i => Array.isArray(i))) {
      for (let index = 0; index < rowList.length; index++) {
        const rowResult = await app.mysql.insert('row', {
          table_id,
          create_time: now,
        });
        if (rowResult.affectedRows) {
          const row_id = rowResult.insertId;
          const cells = fieldList.map((f, i) => {
            const field_id = f.id;
            return {
              row_id,
              field_id,
              content: rowList[index][i] || '',
              create_time: now,
            };
          });
          result = await app.mysql.insert('cell', cells);
        }
      }
    }
    if (result.affectedRows) {
      return true;
    }
  }

  // 查行
  async query(table_id, id, page, pageSize) {
    const { app, service } = this;
    const result = app.response.listResult();
    result.page = page;
    result.pageSize = pageSize;
    const where = { table_id };
    if (id) {
      where.id = id;
    }
    const fieldList = await service.field.query(table_id);
    if (fieldList.length) {
      result.total = await app.mysql.count('row');

      const rowList = await app.mysql.select('row', {
        where,
        orders: [[ 'create_time', 'desc' ], [ 'id' ]],
        ...app.paging(page, pageSize),
      });
      if (rowList.length) {
        // 根据 行 查行字段内容
        const cellItem = rowList.map(item => {
          const row_id = item.id;
          return app.mysql.select('cell', {
            where: { row_id },
          });
        });
        const cellList = await Promise.all(cellItem);
        // 行字段内容根据字段顺序排序
        cellList.forEach((cells, index) => {
          const sortCell = fieldList.map(f => {
            return cells.find(i => i.field_id === f.id);
          });
          // 排完序根据下标顺序生成属性 `$[index]` 对应字段
          sortCell.forEach((item, sindex) => {
            rowList[index][`$${sindex}`] = item;
          });
        });
        result.data = rowList;
      }
    }
    return result;
  }
    //保存图片路径
    async saveImg(row_id,field_id,imgUrl){
      const {app} = this;
      const now = Date.now();
      const rowResult = await app.mysql.update('cell', {
        modify_time: now,
        content:imgUrl
      }, {
        where: { row_id,field_id },
      });
      return rowResult
    }
  // 更新行
  async update(id, rows) {
    const { app, service } = this;
    const now = Date.now();
    const rowResult = await app.mysql.update('row', {
      modify_time: now,
    }, {
      where: { id },
    });
    if (rowResult.changedRows) {
      // 查 表id -> 字段列表 -> 字段排序 -> 更新对应字段内容
      const getRow = await app.mysql.get('row', { id });
      const getTable = await app.mysql.get('table', { id: getRow.table_id });
      const fieldList = await service.field.query(getTable.id);
      const cellList = await app.mysql.select('cell', {
        where: { row_id: id },
      });
      const insertCell = [];
      const updateCell = fieldList.map((field, index) => {
        // 获取更新差异（新增表字段后再update行的情况）
        if (!cellList[index]) {
          insertCell.push({
            row_id: id,
            field_id: field.id,
            create_time: now,
            content: rows[index] || '',
          });
        }
        return {
          row: {
            content: rows[index] || '',
            modify_time: now,
          },
          where: {
            row_id: id,
            field_id: field.id,
          },
        };
      });
      if (insertCell.length) {
        await app.mysql.insert('cell', insertCell);
      }
      const updateResult = await app.mysql.updateRows('cell', updateCell);
      if (updateResult.changedRows) {
        return true;
      }
    }
  }

  // 删除行
  async delete(ids) {
    const { app } = this;
    const all = ids.map(i => +i).map(id => {
      return app.mysql.delete('row', { id });
    });
    await Promise.all(all);
    return true;
  }
}

module.exports = row;
